package org.example.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.Exception.RollBackException;
import org.example.dao.QuestionContentDao;
import org.example.dao.QuestionDao;
import org.example.domain.PageBean;
import org.example.domain.Question;
import org.example.domain.QuestionContent;
import org.example.domain.response.ResponseResult;
import org.example.services.QuestionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Slf4j  //日志
@Transactional  //事务回滚
@Service
public class QuestionServiceImpl implements QuestionService {
    @Resource
    private QuestionDao questionDao;
    @Resource
    private QuestionContentDao questionContentDao;

    //新增
    public Question saveQuestion(Question question){
        try{
            questionDao.insert(question);
            question.getQuestionContent().setQuestionId(question.getQuestionId());
            if(question.getType() != null) questionDao.insertQuestionType(question.getQuestionId(),question.getType());
            if(question.getQuestionContent() != null) questionContentDao.insert(question.getQuestionContent());
            log.info("问题新增成功");
            return question;
        }catch (Exception e){
            e.printStackTrace();
            log.warn("问题新增失败");
            throw new RollBackException("新增问题失败");
        }

    }

    //删除
    @Override
    public boolean deleteQuestion(int id) {
        Question question = questionDao.selectById(id);
        if(question == null){
            log.warn("问题删除：问题基本信息查询失败");
            throw new RollBackException("无该问题，请刷新");
        }
        try {
            questionDao.deleteById(id);
            questionDao.deleteTypeByQuestionId(id);
            questionContentDao.deleteContentByQuestionId(id);
            log.info(question.getQuestionId() + "问题删除成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("删除问题失败");
            throw new RollBackException("问题删除失败");
        }
    }

    //修改
    @Override
    public boolean updateQuestion(Question question) {
        Question questionRes = questionDao.selectById(question.getQuestionId());
        if(questionRes == null){
            log.warn("问题修改：问题基本信息查询失败");
            throw new RollBackException("无该问题信息，请刷新");
        }
        try {
            //修改问题类型
            questionDao.updateById(question);
            //问题类型全删后新加
            if (question.getType() != null) {
                questionDao.deleteTypeByQuestionId(question.getQuestionId());
                questionDao.insertQuestionType(question.getQuestionId(),question.getType());
            }
            //通过questionId查询questionContentId，在通过questionContentId更新
            if (question.getQuestionContent() != null) {
                QuestionContent content = questionContentDao.getContentByQuestionId(question.getQuestionId());
                QuestionContent questionContent = question.getQuestionContent();
                questionContent.setQuestionContentId(content.getQuestionContentId());
                questionContentDao.updateById(questionContent);
            }
            log.info(questionRes.getQuestionId() + "问题修改成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("问题修改失败");
            throw new RollBackException("书籍修改失败");
        }
    }

    //通过问题id 查询问题
    @Override
    public Question getQuestionByQuestionId(int questionId) {
        try {
            Question question = questionDao.selectById(questionId);
            QuestionContent questionContent = questionContentDao.getContentByQuestionId(questionId);
            List<String> types = questionDao.getTypeByQuestionId(questionId);
            question.setQuestionContent(questionContent);
            question.setType(types);
            return question;
        } catch (NullPointerException e) {
            log.warn(questionId + ":通过id查询失败，case: 无该问题id数据");
            throw new RollBackException("无该问题数据");
        } catch (Exception e) {
            log.warn(questionId + ":通过id查询失败，case:" + e.getCause().getMessage());
            throw new RollBackException("查询问题失败");
        }
    }

    //分页条件查询问题，不会查出问题内容
    //条件不能是问题类型和问题内容
    @Override
    public PageBean<Question> getQuestionByPageAndCondition(int pageSize, int currentPage,QueryWrapper wrapper) {
        try {
            IPage<Question> page = new Page<>(currentPage,pageSize);
            //降序显示
            wrapper.orderByDesc("id");
            questionDao.selectPage(page, wrapper);
            PageBean<Question> questionPage = new PageBean<>();
            questionPage.setCurrentPage((int) page.getCurrent());
            questionPage.setPageSize((int) page.getSize());
            questionPage.setTotalPages((int) page.getPages());
            questionPage.setTotalData((int) page.getTotal());
            //查询每条数据的问题类型，分页内容每条数据不展示详细信息
            List<Question> rows = page.getRecords();
            for (Question row : rows) {
                List<String> types = questionDao.getTypeByQuestionId(row.getQuestionId());
                row.setType(types);
            }
            questionPage.setRows(rows);
            log.info("问题分页查询成功");
            return questionPage;
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("分页查询数据失败");
            throw new RollBackException("问题分页查询数据失败");
        }

    }

    //通过问题类型分页查询（模糊）
    @Override
    public PageBean<Question> getQuestionByPageAndType(String type, int pageSize, int currentPage) {
        try {
            type = "%" + type + "%";
//            type = String.format("%%%s%%", type);
            List<Integer> questionIds = questionDao.getQuestionIdByType(type);
            QueryWrapper<Question> wrapper = new QueryWrapper();
            wrapper.in("id",questionIds);
            log.info("按问题类型分页查询成功");
            return getQuestionByPageAndCondition(pageSize,currentPage,wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("按问题类型分页查询失败");
            throw new RollBackException("问题查询失败");
        }
    }

    //通过题目分页查询（模糊）
    @Override
    public PageBean<Question> getQuestionByPageAndTitle(String title, int pageSize, int currentPage) {
        try {
            QueryWrapper<Question> wrapper = new QueryWrapper();
            wrapper.like("title",title);
            log.info("按题目分页查询成功");
            return getQuestionByPageAndCondition(pageSize,currentPage,wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("按题目分页查询失败");
            throw new RollBackException("问题查询失败");
        }
    }

    //分页查询问题
    @Override
    public PageBean<Question> getQuestionByPage(int pageSize, int currentPage) {
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        //调用条件分页查询，条件为null
        return getQuestionByPageAndCondition(pageSize,currentPage,wrapper);
    }


}
